import { existsSync, lstatSync, readdirSync, realpathSync } from "fs";
import { resolve, posix } from "path";

export const appDirectory = realpathSync(process.cwd());
export const resolveApp = (relativePath: string) =>
  resolve(appDirectory, relativePath);
export const SRC_FILE = resolveApp("src");

export const getAliases = (path = SRC_FILE) => {
  const alias: { [key: string]: string } = {};
  const files = readdirSync(path);
  files.forEach((item) => {
    const paths = resolve(path, item);
    const stat = lstatSync(paths);
    if (stat.isDirectory() === true) {
      alias[`@${item}`] = paths;
    }
  });
  return {
    "@": path,
    ...alias,
  };
};

export const getEntry = () => {
  let entry = "";
  for (const name of [
    "index",
    "Index",
    "src/index",
    "src/Index",
    "main",
    "Main",
    "src/main",
    "src/Main",
  ]) {
    for (const ext of [".js", ".ts", ".jsx", ".tsx"]) {
      entry = resolve(name + ext);
      if (existsSync(entry)) {
        return entry;
      }
    }
  }
  return "";
};

export const getHtmlTemplate = (): string => {
  for (const name of [
    "index",
    "public/index",
    "src/index",
    "src/public/index",
    "assets/index",
    "src/assets/index",
  ]) {
    for (const ext of [".html", ".htm"]) {
      const template = resolve(name + ext);

      if (existsSync(template)) {
        return template;
      }
    }
  }
  return "";
};

export const getAssetPath = (assetsDir: string, filePath: string) => {
  return assetsDir ? posix.join(assetsDir, filePath) : filePath
}
